﻿package com.pandemicode.framework.utils {
	import com.pandemicode.framework.interfaces.IDisposeable;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	
	/**
	* @author Michael Lawrence
	* @version 1.0.0
	*/
	public class Disposer {
		/**
		 * A simple class that handles the disposing of various types of objects.
		 */
		public function Disposer() { }
		
		/**
		 * Disposes of the specified objects.
		 * @param	...args		The objects to dispose.
		 */
		public static function dispose(...args):void {
			args.filter(Filter.isDisplayObject).forEach(_disposeDisplayObject);
			args.filter(Filter.isBitmapData).forEach(_disposeBitmapData);
			args.filter(Filter.isLoader).forEach(_disposeLoader);
			args.filter(Filter.isIDisposeable).forEach(_disposeIDisposeable);
		}
		
		private static function _disposeDisplayObject(element:DisplayObject, index:int, array:Array):void {
			if (element.parent != null)
				element.parent.removeChild(element);
		}
		
		private static function _disposeBitmapData(element:BitmapData, index:int, array:Array):void {
			element.dispose();
		}
		
		private static function _disposeIDisposeable(element:IDisposeable, index:int, array:Array):void {
			element.dispose();
		}
		
		private static function _disposeLoader(element:Loader, index:int, array:Array):void {
			var li:LoaderInfo = element.contentLoaderInfo;
			if(li.childAllowsParent && li.content is Bitmap)
				(li.content as Bitmap).bitmapData.dispose();
			element.unload();
		}
	}
}